<template>
  <div class="page">
    <div class="login">
      <div class="login-title">登录</div>
      <el-form ref="ruleFormRef" :rules="rules" style="width: 100%" :model="ruleForm">
        <el-form-item prop="username">
          <el-input class="input" v-model="ruleForm.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input class="input" v-model="ruleForm.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button
            style="width: 100%; height: 0.5rem"
            type="primary"
            @click="submitForm(ruleFormRef)"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts"></script>

<script setup lang="ts">
import { ElInput, ElFormItem, ElForm, ElButton } from 'element-plus'
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import api from '@/api'
import crypto from '@/utils/crypto'
import { useUserStore } from '@/stores/user'
import { useRoute, useRouter } from 'vue-router'

const userStore = useUserStore()
const ruleForm = reactive({
  username: '',
  password: '',
})
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})

const route = useRoute()
const router = useRouter()

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      login()
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 登录接口
const login = async () => {
  try {
    const Info = {
      username: ruleForm.username,
      password: crypto.md5(ruleForm.password),
    }

    const res = await api.user.login(Info)
    if (res.success) {
      userStore.token = res.data.token

      router.push('/HomePage')
    }
  } catch (error) {
    console.log(error, 'error')
  }
}
</script>

<style scoped lang="scss">
.page {
  width: 100%;
  height: 100vh;
  background-color: red;
  box-sizing: border-box;
}
.login {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  width: 6.16rem;
  height: 6.66rem;

  position: absolute;
  top: 1.5rem;
  right: 1rem;

  padding: 0 0.6rem;
  background-color: #fff;
  border-radius: 0.16rem;
}
.login-title {
  font-size: 0.32rem;
  font-weight: 700;
  margin-bottom: 0.4rem;
}
.input {
  width: 100%;
  height: 0.48rem;
  :deep(.el-input__prefix) {
    font-size: 0.18rem;
  }
}
</style>
